﻿using System;
using System.IO;

namespace Calendar.Logic.Log
{
    public class LogFile : LoggerEventHandler
    {
        private bool _active;
        private string _logFolder;

        public LogFile()
        {
            _active = false;
        }

        public string LogFolder
        {
            set
            {
                _logFolder = value;
                try
                {
                    if (!Directory.Exists(_logFolder))
                        Directory.CreateDirectory(_logFolder);

                    _active = true;
                    start();
                }
                catch (Exception exc)
                {
                    LogManager.LoggerError(exc.Message);
                }
            }
        }

        private static string LinePrefix(LoggerMessage logMsg)
        {
            var format = "{0} - ";
            switch (logMsg.Level)
            {
                case DsLogLevel.CRITICAL:
                    format += "[CRITICAL|{1}.{2}()] - ";
                    break;
                case DsLogLevel.ERROR:
                    format += "[ERROR|{1}] - ";
                    break;
                case DsLogLevel.WSERROR:
                    format += "[WSERROR] - ";
                    break;
                case DsLogLevel.WARNING:
                    format += "[WARNING|{1}] - ";
                    break;
                case DsLogLevel.INFO:
                    format += "[INFO] - ";
                    break;
                case DsLogLevel.DEBUG:
                    format += "[DEBUG|{1}.{2}()] - ";
                    break;
                default:
                    break;
            }
            return string.Format(format, logMsg.Time.ToString("dd.MM.yyyy HH:mm:ss"), logMsg.Class, logMsg.Method);

        }

        private void Write(string msg, bool isError)
        {
            var fileName = string.Format("{0}__{1}.log", DateTime.Now.ToString("yyyy.MM.dd"), isError ? "Error" : "Msg");

            try
            {
                var st = new StreamWriter(_logFolder + fileName, true);
                st.WriteLine(msg);
                st.Close();
            }
            catch (Exception exc)
            {
                LogManager.LoggerError(exc.Message);
            }           
        }

        protected override void log(LoggerMessage logMsg)
        {
            if (!_active) return;
            var lineMsg = string.Format("СООБЩЕНИЕ: {0}  КОММЕНТАРИЙ: {1}", logMsg.Msg, logMsg.Comm);
            Write(LinePrefix(logMsg) + lineMsg, logMsg.Level < DsLogLevel.WARNING);
        }

        protected override void onShutdown()
        {
           //throw new NotImplementedException();
        }
    }
}
